<?php

namespace App\Service\Assets;

use App\Models\Assets\ExpensesModel;
use App\Models\Assets\RevenuesModel;
use Carbon\Carbon;

class AssetsService
{
    /**
     * 汇总收益
     * @param $userId
     * @param null $time
     * @return int
     */
    public static function revenues($userId, $time = null): int
    {
        if ($time == null) {
            $time      = Carbon::now();
            $startTime = $time->startOfDay()->timestamp + 5 * 60 * 60;
            $endTime   = $time->endOfDay()->timestamp;
        } else {
            $startTime = $time->startOfDay()->timestamp;
            $endTime   = $time->endOfDay()->timestamp + 5 * 60 * 60;
        }

        return (int)RevenuesModel::query()
            ->where('user_id', $userId)
            ->whereBetween('created_at', [$startTime, $endTime])
            ->sum('amount');
    }


    /**
     * 汇总支出
     * @param $userId
     * @param $time
     * @return int
     */
    public static function expenses($userId, $time = null): int
    {
        if ($time == null) {
            $time = Carbon::now();
        }

        return (int)ExpensesModel::query()
            ->where('user_id', $userId)
            ->whereBetween('created_at', [$time->startOfDay()->timestamp, $time->endOfDay()->timestamp])
            ->sum('amount');
    }
}